﻿using System;
using App.Entity;
using App.IServices;
using App.IRepository;
using System.Collections.Generic;
using App.Code;


/*!
* 文件描述：一切从简，只为了更懒！
*/
namespace App.Services
{
	public partial class Sys_DbBackupServices : BaseServices<Sys_DbBackup> , ISys_DbBackupServices
	{
		ISys_DbBackupRepository _ISys_DbBackupRepository;
		public Sys_DbBackupServices(ISys_DbBackupRepository __ISys_DbBackupRepository)
		{
			this._ISys_DbBackupRepository = __ISys_DbBackupRepository;
			base._IBaseRepository = __ISys_DbBackupRepository;
		}

        public void DeleteForm(string keyValue)
        {
            _ISys_DbBackupRepository.Delete(c => c.Id == keyValue);
        }

        public void ExecuteDbBackup(Sys_DbBackup dbBackupEntity)
        {
            #region 备份
            _ISys_DbBackupRepository.ExecuteCommand(string.Format("backup database {0} to disk ='{1}'", dbBackupEntity.DbName, dbBackupEntity.FilePath));          
            dbBackupEntity.FileSize = FileHelper.ToFileSize(FileHelper.GetFileSize(dbBackupEntity.FilePath));
            dbBackupEntity.FilePath = "/Resource/DbBackup/" + dbBackupEntity.FileName;
            #endregion
            _ISys_DbBackupRepository.Insert(dbBackupEntity);
        }

        public Sys_DbBackup GetForm(string keyValue)
        {
            return _ISys_DbBackupRepository.QuerySingle(c => c.Id == keyValue);
        }

        public List<Sys_DbBackup> GetList(string queryJson)
        {
            var expression = ExtLinq.True<Sys_DbBackup>();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                string condition = queryParam["condition"].ToString();
                string keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "DbName":
                        expression = expression.And(t => t.DbName.Contains(keyword));
                        break;
                    case "FileName":
                        expression = expression.And(t => t.FileName.Contains(keyword));
                        break;
                }
            }
            return _ISys_DbBackupRepository.QueryByWhere(expression, "BackupTime");
        }

        public void SubmitForm(Sys_DbBackup dbBackupEntity)
        {
            dbBackupEntity.Id = Common.GuId();
            dbBackupEntity.EnabledMark = true;
            dbBackupEntity.BackupTime = DateTime.Now;
            dbBackupEntity.CreatorTime = DateTime.Now;
            ExecuteDbBackup(dbBackupEntity);
        }
    }
}